package com.xx.happychatboot.middleware.netty.strategy.websocket;

import com.xx.happychatboot.base.utils.RedisUtils;
import com.xx.happychatboot.middleware.netty.constants.WebSocketConstants;
import com.xx.happychatboot.middleware.netty.constants.WebSocketRedisConstants;
import com.xx.happychatboot.middleware.netty.domain.enums.WebSocketCallBackEnums;
import com.xx.happychatboot.middleware.netty.domain.enums.WebSocketTypeEnum;
import com.xx.happychatboot.middleware.netty.domain.vo.response.WebSocketResponse;
import com.xx.happychatboot.middleware.netty.service.WebSocketService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 心跳策略
 */
@Component
@Slf4j
public class HeartStrategy extends AbstractWebsocketStrategy{
    @Autowired
    private WebSocketService webSocketService;

    @Override
    protected WebSocketTypeEnum getStrategyCode() {
        return WebSocketTypeEnum.HEARTBEAT;
    }

    /**
     * 心跳检测执行方法
     * @param ctx
     * @param data
     */
    @Override
    public void execute(ChannelHandlerContext ctx, String data) {
        // 响应心跳
        webSocketService.sendMsg(ctx.channel(),
                WebSocketResponse.callBackType(WebSocketCallBackEnums.HEARTBEAT_CALL_BACK.getType()));

        // 设置属性
        AttributeKey<Long> heartBeatAttr = AttributeKey.valueOf(WebSocketConstants.HEARTBEAT_TIMES);
        Long heartbeatTimes = ctx.channel().attr(heartBeatAttr).get();
        ctx.channel().attr(heartBeatAttr).set(++heartbeatTimes);
        if (heartbeatTimes % 10 == 0) {
            // 每心跳10次，用户在线状态续一次命
            AttributeKey<Long> userIdAttr = AttributeKey.valueOf(WebSocketConstants.USER_ID);
            Long userId = ctx.channel().attr(userIdAttr).get();
            String key = WebSocketRedisConstants.WEB_SOCKET_USER_SERVER_ID + userId;
            RedisUtils.set(key, ctx.channel().id().asLongText(), WebSocketRedisConstants.ONLINE_TIMEOUT_SECOND, TimeUnit.SECONDS);
        }
        AttributeKey<Long> userIdAttr = AttributeKey.valueOf(WebSocketConstants.USER_ID);
        Long userId = ctx.channel().attr(userIdAttr).get();
        log.info("心跳,userId:{},{}",userId,ctx.channel().id().asLongText());
    }
}
